package org.jeecg.common.util;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileUtils {

    public static ResponseEntity<byte[]> createByteArray(File file){
        HttpHeaders headers = new HttpHeaders();
        // 设置http响应类型为二进制数据流
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> ba =  new ResponseEntity<byte[]> (readFileToByteArray(file), headers, HttpStatus.OK);
        return  ba;
    }

    public static byte[] readFileToByteArray(File file) {
        byte[] data = null;
        FileInputStream is = null;
        ByteArrayOutputStream byteOut = null;
        try {
            is = new FileInputStream(file);
            byteOut = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                byteOut.write(buffer, 0, len);
            }
            data = byteOut.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(byteOut != null) {
                try {
                    byteOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data;
    }
}
